package com.itheima.service.impl;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.dto.OrderDTO;
import com.itheima.mapper.MemberMapper1;
import com.itheima.mapper.OrderMapper1;
import com.itheima.mapper.OrdersettingMapper1;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.vo.OrderVO;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrdersettingMapper1 ordersettingMapper1;
    @Autowired
    private MemberMapper1 memberMapper1;
    @Autowired
    private OrderMapper1 orderMapper1;
    /**
     * 体检预约
     * @param orderDTO
     */
    @Override
    @Transactional
    public Result submitOrder(OrderDTO orderDTO) throws ParseException {
        // 1 手机号和验证码不能为空
        String telephone = orderDTO.getTelephone();
        String validateCode = orderDTO.getValidateCode();
        if (telephone == null || telephone.isEmpty() || validateCode == null || validateCode.isEmpty()){
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL, null);
        }

        // 2 检验验证码是否正确
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String code = valueOperations.get(telephone + RedisMessageConstant.SENDTYPE_ORDER).toString(); //redis中缓存的验证码
        if (!validateCode.equals(code)){
            // 验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR, null);
        }

        // 3 查询预约日期的可预约人数是否设置，没有设置就不能预约
        String stringDate = orderDTO.getOrderDate();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date orderDate = simpleDateFormat.parse(stringDate);
        OrderSetting orderSetting = ordersettingMapper1.findByDate(orderDate);
        if (orderSetting == null){
            // 预约日期没有设置可预约人数，不能预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER, null);
        }

        // 4 查询预约日期的可预约人数是否已经约满
        if (orderSetting.getNumber() == orderSetting.getReservations()){
            // 已经约满
            return new Result(false, MessageConstant.ORDER_FULL, null);
        }

        // 5 判断是否重复预约，即判断同一个用户同一天是否预约了同一个套餐
        Member member = memberMapper1.findByIdCard(orderDTO.getIdCard());
        if (member != null){
            // 重复预约
            int count = orderMapper1.find(member.getId(), orderDate, orderDTO.getSetmealId());
            if (count > 0){
                return new Result(false, MessageConstant.HAS_ORDERED, null);
            }
        }else{
            // 6 说明该用户不是会员，需自动完成注册
            member = new Member();
            BeanUtils.copyProperties(orderDTO, member);
            member.setPhoneNumber(orderDTO.getTelephone());
            member.setRegTime(orderDate);
            memberMapper1.add(member);
        }

        // 7 向预约表插入预约信息
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO, order);
        order.setMemberId(member.getId());
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setOrderDate(orderDate);
        orderMapper1.add(order);

        // 8 更新预约人数
        OrderSetting orderSetting1 = new OrderSetting();
        orderSetting1.setReservations(orderSetting.getReservations() + 1);
        orderSetting1.setOrderDate(orderDate);
        ordersettingMapper1.updateReservation(orderSetting1);

        // 8 返回预约成功结果
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    /**
     * 根据预约id查询预约信息
     * @param id
     * @return
     */
    @Override
    public OrderVO findById(Integer id) {
        Map map = orderMapper1.findById(id);
        System.out.println(map);
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderDate(map.get("orderDate").toString());
        orderVO.setOrderType((String) map.get("orderType"));
        orderVO.setMember((String) map.get("name"));
        orderVO.setSetmeal((String) map.get("setmeal"));
        return orderVO;
    }
}
